package com.itheima.aspect;

import com.itheima.entity.OperateLog;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

//@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;


    @Around("@annotation(com.itheima.aspect.Log)")
    public Object addLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //开始时间
        long begin = System.currentTimeMillis();
        //调用原始方法
        Object object = joinPoint.proceed();
        //结束时间
        long end = System.currentTimeMillis();
        //获取耗时
        long costTime=end-begin;

        //获取操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        //创建对象

        OperateLog oLog=new OperateLog(null, CurrentHolder.getCurrentId(), LocalDateTime.now(),className,methodName,methodParams,object!=null?object.toString():"void",costTime);

        //保存日志

        log.info("log:{}",oLog);

        operateLogMapper.insert(oLog);
        return object;

    }
}
